package com.example.ai.inventory.service;

import com.example.ai.inventory.entity.Product;
import com.example.ai.inventory.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品服务实现类
 */
@Service
public class ProductServiceImpl implements ProductService {
    
    @Autowired
    private ProductRepository productRepository;
    
    @Override
    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }
    
    @Override
    public Product getProductById(Long id) {
        return productRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("商品不存在：" + id));
    }
    
    @Override
    public Product getProductByCode(String code) {
        return productRepository.findByCode(code)
                .orElseThrow(() -> new RuntimeException("商品不存在：" + code));
    }
    
    @Override
    public Product addProduct(Product product) {
        // 验证商品编码是否重复
        productRepository.findByCode(product.getCode()).ifPresent(p -> {
            throw new RuntimeException("商品编码已存在：" + product.getCode());
        });
        
        // 初始库存默认为0
        if (product.getStock() == null) {
            product.setStock(0);
        }
        
        return productRepository.save(product);
    }
    
    @Override
    @Transactional
    public Product updateProduct(Product product) {
        // 验证商品是否存在
        Product existing = getProductById(product.getId());
        
        // 验证商品编码是否重复（排除当前商品）
        if (!existing.getCode().equals(product.getCode())) {
            productRepository.findByCode(product.getCode()).ifPresent(p -> {
                throw new RuntimeException("商品编码已存在：" + product.getCode());
            });
        }
        
        // 保留原有的库存和版本号
        product.setStock(existing.getStock());
        product.setVersion(existing.getVersion());
        
        return productRepository.save(product);
    }
    
    @Override
    public void deleteProduct(Long id) {
        // 检查是否有相关的采购或销售记录
        // 这里可以添加业务逻辑，比如检查是否有相关的采购或销售记录
        productRepository.deleteById(id);
    }
    
    @Override
    public List<Product> getProductsByCategoryId(Long categoryId) {
        return productRepository.findByCategoryId(categoryId);
    }
    
    @Override
    public List<Product> searchProducts(String keyword) {
        return productRepository.findByNameContaining(keyword);
    }
    
    @Override
    @Transactional
    public void updateProductStock(Long productId, int quantity) {
        Product product = getProductById(productId);
        
        // 计算新库存
        int newStock = product.getStock() + quantity;
        
        // 检查库存是否合法
        if (newStock < 0) {
            throw new RuntimeException("库存不足，无法操作");
        }
        
        // 更新库存
        product.setStock(newStock);
        
        // 乐观锁版本号递增
        product.setVersion(product.getVersion() + 1);
        
        productRepository.save(product);
    }
}